package com.waijiaojun.tpo;

import com.waijiaojun.tpo.entity.SystemAccessLog;
import com.waijiaojun.tpo.repository.SystemAccessLogDao;
import com.waijiaojun.tpo.utils.IPUtil;
import com.waijiaojun.tpo.web.PaymentController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;

/**
 * Created by Peter on 2018/1/29.
 */
@Order(1)
@WebFilter(filterName = "appFilter", urlPatterns = "/*")
public class AppFilter implements Filter {
    private static Logger logger = LoggerFactory.getLogger(AppFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        if (uri.contains("css") || uri.contains("js")|| uri.contains("img") || uri.contains("fonts")|| uri.contains("image")|| uri.contains("bootstrap3")) {
            logger.info("static resources：" + uri);
        } else {
            printHttpHeader(request);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

    private void printHttpHeader(HttpServletRequest request) throws IOException {
        Enumeration headerNames = request.getHeaderNames();
        String uri = request.getRequestURI();
        String method = request.getMethod();
        String clientIp = IPUtil.getIp(request);
        String msg = new String("\n----------------  Http Header [" + clientIp + "]---------------\n");
        msg = msg + method + " " + uri + "\n";
        StringBuffer header = new StringBuffer();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            header.append(key + ":" + value + "\n");
        }
        header.append("\n");
        msg = msg + header.toString();
        logger.info(msg);


    }
}
